<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 运费订单
 *
 * @icon fa fa-circle-o
 */
class DeliveryOrder extends Backend
{

    /**
     * DeliveryOrder模型对象
     * @var \app\admin\model\DeliveryOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\DeliveryOrder;

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['car', 'driver', 'owner', 'project'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $uid = $params['uid'];
            $user = Db::name('user')->where('id',$uid)->find();
            if($user['cate'] !== 0) {
                $this->error('选择的用户存在身份');
            }
            $result = $this->model->save($params);
            Db::name('user')->where('id',$uid)->update(['cate'=>2]);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error($this->model->getError());
            }
        }
        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error($row->getError());
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
